package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import io.micrometer.core.instrument.binder.BaseUnits;
import org.apache.commons.collections4.BagUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 订单结算
     * @return
     */
    @Override
    public TradeVo orderTradeData() {
        Long userId = SecurityContextHolder.getUserId();
        //远程调用 被选中的商品
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if (R.FAIL==cartCheckedListResult.getCode()){
            throw new ServiceException(cartCheckedListResult.getMsg());
        }
        //获取购物车
        List<CartInfo> cartInfosList = cartCheckedListResult.getData();
        if (CollectionUtils.isEmpty(cartInfosList)){
            throw new ServiceException("数据不存在");
        }
        //CartInfo 转为 OrderItem
        List<OrderItem> orderItemsList = cartInfosList.stream().map((cartInfo) -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);//对象属性赋值
            return orderItem;
        }).toList();

        //总额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemsList) {
            BigDecimal multiply = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));
            totalAmount.add(multiply);
        }

        //交易号
        String tradeNo=generateTradeNo(userId);
        //封装对象
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTradeNo(tradeNo);//交易号
        tradeVo.setOrderItemList(orderItemsList);//结算商品列表
        tradeVo.setTotalAmount(totalAmount);//总额
        return null;
    }
    @NotNull //确保方法参数、返回值或类字段不能为 null
    private String generateTradeNo(Long userId){
        String tradeNo= UUID.randomUUID().toString().replaceAll("-","");
        String userTradeKey = "user:tradeNo:" + userId;
        //存储到redis
        redisTemplate.opsForValue().set(userTradeKey,tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1.验证用户重复提交表单
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey="user:tradeNo:"+userId;
        String tradeNoFormForm = orderForm.getTradeNo();//表单交易流水号
        String script="if redis.call('get',KEYS[1])==ARGV[1]\n" +
                "then\n" +
                "return redis.call('del',KEYS[1])\n" +
                "else\n" +
                "return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript=new DefaultRedisScript<>(script, Long.class);
        Long count = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), tradeNoFormForm);
        if (count==0){
            throw new ServiceException("重复提交");
        }
        //2.验证表单参数是否空
        List<OrderItem> orderItemList = orderForm.getOrderItemList();//购物车
        if (CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("数据不存在");
        }
        //3.校验价格变化
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL==skuPriceListResult.getCode()){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData();//数据库
        //转Map
        Map<Long, BigDecimal> skuIdToSkuPriceMap = skuPriceList.stream().
                collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));
        StringBuilder resultStr=new StringBuilder("");
        for (OrderItem orderItem : orderItemList) {
            BigDecimal skuPriceFormDb = skuIdToSkuPriceMap.get(orderItem.getSkuPrice());
            if (orderItem.getSkuPrice().compareTo(skuPriceFormDb) !=0){
                resultStr.append("价格["+orderItem.getSkuName()+"]有变动");
            }
        }
        if (resultStr.toString().length()>0){
            throw new ServiceException(resultStr.toString());
        }
        //4.校验库存锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map((orderItem) -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setIsHaveStock(false);
            return skuLockVo;
        }).toList();
        R<String> checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL==checkAndLockResult.getCode()){
            throw new ServiceException(checkAndLockResult.getMsg());
        }
        String checkAndLockResultStr = checkAndLockResult.getData();
        if (StringUtils.isNotEmpty(checkAndLockResultStr)){
           throw new ServiceException(checkAndLockResultStr);
        }
        //5.保存订单（订单表、订单项表、订单日志表）

        Long orderId=null;
        try {
           orderId=this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }
        //6.删除购物车选中商品
          remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);
        //7.发送延迟消息 15分钟等待
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                orderId.toString(),
                MqConst.CANCEL_ORDER_DELAY_TIME);
        return orderId;
    }

    @Transactional
    private Long saveOrder(OrderForm orderForm) {
        //保存订单
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setRemark(orderForm.getRemark());
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount=new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
          totalAmount=totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        orderInfo.setOrderStatus(0);
        UserAddress userAddress = remoteUserAddressService.
                getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
       orderInfo.setReceiverName(userAddress.getName());
       orderInfo.setReceiverPhone(userAddress.getPhone());
       orderInfo.setReceiverTagName(userAddress.getTagName());
       orderInfo.setReceiverProvince(userAddress.getProvinceCode());
       orderInfo.setReceiverCity(userAddress.getCityCode());
       orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
       orderInfo.setReceiverAddress(userAddress.getFullAddress());
       orderInfoMapper.insert(orderInfo);

       //订单项
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            orderItemMapper.insert(orderItem);
        }

        //订单日志

        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLog.setProcessStatus(0);
        orderLogMapper.insert(orderLog);
        return null;
    }

    /**
     * 关闭订单
     * @param orderId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processCloseOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if (null!=orderId && orderInfo.getOrderStatus().intValue()==0 ){
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //日志记录
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统自动取消");
            orderLogMapper.insert(orderLog);

            //发送消息 解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderInfo.getOrderNo());
        }
    }

    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));
        List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));
        orderInfo.setOrderItemList(orderItems);
        return orderInfo;
    }

    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo).
                select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if (orderInfo.getOrderStatus().intValue()==0){
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}